package ams.action;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ModelDriven;

import ams.model.dto.Login;
import ams.model.entity.Rights;
import ams.service.ILoginService;
import ams.service.IUserService;
import ams.util.SysConstans;

@Namespace("/login")
public class LoginAction extends BaseAction<Login> implements ModelDriven<Login> {

	private static final long serialVersionUID = 1L;

	private Login login = new Login();

	@Autowired
	private ILoginService loginService;

	@Autowired
	private IUserService userService;
	
	private List<Rights> rightsList = new ArrayList<>();
	

	@Action(value = "userLogin", results = { @Result(location = "/WEB-INF/jsp/index.jsp"),
			@Result(name = "error", location = "/login.jsp") })
	public String userLogin() {
		
		Map<String, Object> session = ActionContext.getContext().getSession();
		//获取正确的验证码值
		String captchaSessionKey = (String) session.get(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
		//先比较验证码，不一致不再比较账户密码
		if(!StringUtils.equalsIgnoreCase(captchaSessionKey, login.getCaptcha())){
			return ERROR;
		}
		boolean isAllowed = loginService.isAllowed(login);
		if (isAllowed) {
			session.put(SysConstans.SESSION_LOGIN_ACCOUNT, login.getAccount());
			List<Rights> rightsList = userService.getUserRights(login.getAccount());
			List<String> urlList = new ArrayList<>();
			for (Rights rigths : rightsList) {
				urlList.add(rigths.getUrl());
			}
			session.put(SysConstans.SESSION_URL_LIST, urlList);
			return SUCCESS;
		}
		return ERROR;
	}
	
	@Action(value="getMenu",results={
			@Result(type="json",params={ "root", "rightsList", "excludeNullProperties", "true"})})
	public String getMenu(){
		Map<String, Object> session = ActionContext.getContext().getSession();
		String loginAccount = (String)session.get(SysConstans.SESSION_LOGIN_ACCOUNT);
		rightsList = userService.getUserRights(loginAccount);
		return SUCCESS;
	}

	@Action(value = "welcome", results = { @Result(location = "/WEB-INF/jsp/welcome.jsp") })
	public String welcome() {
		return SUCCESS;
	}

	@Override
	public Login getModel() {
		return login;
	}

	public List<Rights> getRightsList() {
		return rightsList;
	}

	public void setRightsList(List<Rights> rightsList) {
		this.rightsList = rightsList;
	}
	
}
